package sample;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.Event;
import com.google.wave.api.EventType;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;

/**
 * Handles events whenever a conversation is updated
 * @author ago
 *
 */
@SuppressWarnings("serial")
public class RobotServlet extends AbstractRobotServlet {
	@SuppressWarnings("unchecked")
  public void processEvents(RobotMessageBundle bundle) {
	  PersistenceManager pm = PMF.get().getPersistenceManager();
		Wavelet wavelet = bundle.getWavelet();
		
		if(bundle.wasSelfAdded()) {
	    String query = "select from " + User.class.getName();
	    List<User> users = (List<User>) pm.newQuery(query).execute();
		  for(User user : users) {
		    wavelet.addParticipant(user.getUsername());
		  }
		  
			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView.append("Added participants");
		}
		
		String waveId = wavelet.getWaveId();
    String title = wavelet.getTitle();
    List<String> participants = wavelet.getParticipants();
    WaveletRecord waveletRecord = new WaveletRecord(waveId, title, participants.size());
    pm.makePersistent(waveletRecord);
     
    for(Event e : bundle.getEvents()) { 
      if(e.getType() == EventType.BLIP_SUBMITTED) { 
        String blipId = e.getBlip().getBlipId();
        String author = e.getBlip().getCreator();
        String text = e.getBlip().getDocument().getText();
        String parentBlipId = e.getBlip().getParentBlipId();
        //int level = getLevel(e);
        int level = 0;
        
        List<String> childBlipIds = e.getBlip().getChildBlipIds();
        BlipRecord blipRecord = new BlipRecord(blipId, waveId, author, text, parentBlipId, childBlipIds, level);
        pm.makePersistent(blipRecord);
      } 
    }
    
    pm.close();    
	}

  private int getLevel(Event e) {
    int level = 0;
    Blip currentBlip = e.getBlip();
    while(currentBlip != null) {
      level++;
      currentBlip = currentBlip.getParent();
    }
    return level;
  }
}
